package com.summer.shopping.config;

import com.summer.shopping.domain.properties.JwtProperties;
import com.summer.shopping.fun.handlers.userId.GetUserIdHandler;
import com.summer.shopping.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@Slf4j
public class DefaultHandlerConfig {

    @Autowired
    JwtProperties jwtProperties;
    @Bean
    @ConditionalOnMissingBean
    public GetUserIdHandler getUserIdHandler(){
        return new DefaultGetUserIdHandler();
    }

    public class DefaultGetUserIdHandler implements GetUserIdHandler{
        @Override
        public Long getUserIdByToken(String token) {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token);
//            log.info("{}",claims.get("userId"));
            Integer userId = (Integer) claims.get("userId");

            return Long.parseLong(userId.toString());
//            return null;
        }

        @Override
        public Integer getPermissionByToken(String token) {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token);
            return (Integer) claims.get("permission");
        }
    }
}
